package com.spring.blog.common.interceptor;

import com.spring.blog.common.constant.Constants;
import com.spring.blog.common.util.JWTUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component //组件层
public class LoginInterceptor implements HandlerInterceptor {//配置拦截器

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token=request.getHeader(Constants.USER_TOKEN);
        log.info("从header中获取token:"+token);
        if(token==null){
            log.error("令牌为null,没有登陆");
            //401没有登陆 403无权限
            response.setStatus(401);
            return false;
        }
        //验证令牌是否正确
        Claims claims = JWTUtils.parseJWT(token);
        if(claims==null){
            log.error("令牌信息错误");
            response.setStatus(401);
            return false;
        }
        return true;
    }
}
